package com.qf.controller;

import com.feign.HotalFeign;
import com.qf.entity.Hotal;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/hotal")
public class SystemHotalController {

    @Autowired
    private HotalFeign hotalFeign;

    private String uploadPath = "C:/worker/img";

    /**
     * 酒店列表页
     * @return
     */
    @RequestMapping("/list")
    public String hotalList(Model model){
        //访问酒店服务，获得酒店信息
        List<Hotal> hotals = hotalFeign.queryList().getData();
        model.addAttribute("hotals", hotals);
        return "hotallist";
    }

    /**
     * 新增酒店
     * @return
     */
    @RequestMapping("/insert")
    public String hotalInsert(MultipartFile file, Hotal hotal){
        System.out.println("添加酒店信息：" + hotal);

        String outPath = uploadPath + "/" + UUID.randomUUID().toString();

        //处理图片上传
        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(outPath);
        ){
            //文件拷贝
            IOUtils.copy(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }

        hotal.setHotalImage(outPath);

        //通过Feign调用酒店服务，添加酒店信息
        hotalFeign.insert(hotal);

        return "redirect:/system/hotal/list";
    }

    /**
     * 获取图片资源
     */
    @RequestMapping("/getImage")
    public void getImage(String path, HttpServletResponse response) {
        //图片输入流
        try (
                InputStream in = new FileInputStream(path);
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
